<template>
  <div>
    <h1>订单列表</h1>
    <!-- 查询 -->
    <el-form :inline="true" :model="pageFrom" class="demo-form-inline">
      <el-form-item label="关键字">
        <el-input
          v-model="pageFrom.keyWord"
          placeholder="请输入名称/id"
          clearable
        />
      </el-form-item>
      <el-form-item label="状态">
        <el-select
          v-model="pageFrom.orderStatus"
          placeholder="请选择状态"
          style="width: 140px"
          clearable
        >
          <el-option label="未支付" :value="0" />
          <el-option label="已支付" :value="1" />
          <el-option label="待发货" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="类型">
        <el-select
          v-model="pageFrom.typeId"
          placeholder="请选择类型"
          style="width: 140px"
          clearable
        >
          <el-option
            v-for="item in typeList"
            :label="item.dictName"
            :value="item.dictValue"
            :key="item.dictId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="loadOrderList">查询</el-button>
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="exportOrder()">导出</el-button>
    <el-button type="danger" @click="onDeleteBatchOrder()">删除</el-button>
    <el-button type="success" @click="onAddOrder()">添加订单</el-button>
    <!-- 表格 -->
    <el-table
      :data="tableData"
      stripe
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="orderId" label="序号" />
      <el-table-column prop="orderNo" label="订单号" />
      <el-table-column prop="typeName" label="订单类型" />
      <el-table-column prop="prodInfo" label="商品信息" />
      <el-table-column prop="orderStatus" label="订单状态">
        <template #default="scope">
          <el-tag type="warning" v-if="scope.row.orderStatus == 0"
            >未支付</el-tag
          >
          <el-tag type="success" v-if="scope.row.orderStatus == 1"
            >已支付</el-tag
          >
          <el-tag type="Info" v-if="scope.row.orderStatus == 2">待发货</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="orderAmount" label="订单金额" />
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column label="操作">
        <el-button type="success">详情</el-button>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div style="margin-top: 20px">
      <el-pagination
        v-model:current-page="pageFrom.pageNum"
        v-model:page-size="pageFrom.pageSize"
        :page-sizes="[2, 4, 6, 8]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 添加订单 -->
    <div>
      <el-dialog v-model="dialogFormVisible" title="添加订单" width="500">
        <el-form :model="form">
          <el-form-item label="商品名称" :label-width="formLabelWidth">
            <el-select
              v-model="form.infoId"
              placeholder="请选择商品名称"
              style="width: 240px"
            >
              <el-option
                v-for="item in infoList"
                :key="item.infoId"
                :label="item.prodName"
                :value="item.infoId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="Zones" :label-width="formLabelWidth">
            <el-input-number v-model="form.num" :min="1" />
          </el-form-item>
          <el-button type="success" @click="onAddInfo()">添加</el-button>
          <el-table :data="infoData" stripe style="width: 100%">
            <el-table-column prop="infoId" label="商品Id" />
            <el-table-column prop="prodName" label="商品名称" />
            <el-table-column prop="prodPrice" label="商品价格" />
            <el-table-column prop="num" label="商品数量" />
            <el-table-column label="操作">
              <template #default="scope">
                <el-button type="danger" @click="removeInfo(scope.row)"
                  >移除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <span>合计:{{ totalAmount }}元</span>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="saveOrder()"> 确认 </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { onMounted, ref } from "vue";
import { getOrderList, deleteBatchOrder, addOrder } from "@/api/order";
import { getDictByType, prodInfoList } from "@/api/prod";
import { da } from "element-plus/es/locales.mjs";

import { ElMessage, type TableInstance } from "element-plus";
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const multipleTableRef = ref<TableInstance>();
const multipleSelection = ref<any[]>([]);
const tableData = ref([]);
const typeList = ref([]);
const infoData = ref([]);
const infoList = ref([]);
const total = ref(0);
const totalAmount = ref(0);
const user = ref({
  userName: null,
  userId: null,
});

const form = ref({
  num: null,
  infoId: null,
});

const pageFrom = ref({
  pageNum: 1,
  pageSize: 2,
  keyWord: null,
  orderStatus: null,
  typeId: null,
});
const saveOrder = () => {
  addOrder(infoData.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("添加订单成功");
      dialogFormVisible.value = false;
      loadOrderList();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};
//追加商品信息
const onAddInfo = () => {
  infoList.value.forEach((item) => {
    if (item.infoId == form.value.infoId) {
      item.num = form.value.num;
      infoData.value.push(item);
    }

    //计算总价
    totalAmount.value = 0;
    infoData.value.forEach((item) => {
      totalAmount.value += item.prodPrice * item.num;
    });
  });
};

//移除
const removeInfo = (row: any) => {
  infoList.value.forEach((item, index) => {
    if (item.infoId == row.infoId) {
      infoData.value.splice(index, 1);
    }

    //重新计算
    totalAmount.value = 0;
    infoData.value.forEach((item) => {
      totalAmount.value += item.prodPrice * item.num;
    });
  });
};

//添加订单框
const onAddOrder = () => {
  dialogFormVisible.value = true;
};
//加载商品信息
const loadProdInfoList = () => {
  prodInfoList().then((res) => {
    infoList.value = res.data.data;
  });
};

//复选框赋值
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
};
//批量删除
const onDeleteBatchOrder = () => {
  let ids: any = [];
  multipleSelection.value.forEach((item) => {
    ids.push(item.orderId);
  });
  if (ids.length <= 0) {
    ElMessage.error("至少选择一条数据");
    return;
  }
  deleteBatchOrder(ids).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("删除成功");
      loadOrderList();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};
//导出
const exportOrder = () => {
  let u = sessionStorage.getItem("user");
  user.value.userId = JSON.parse(u).userId;
  let path =
    "http://localhost:9002/product/product/exportOrder/" + user.value.userId;
  window.open(path);
};

//列表
const loadOrderList = () => {
  getOrderList(pageFrom.value).then((res) => {
    tableData.value = res.data.data.records;
    total.value = res.data.data.total;
  });
};
//每页条数
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  pageFrom.value.pageSize = val;
  loadOrderList();
};
//当前页数
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  pageFrom.value.pageNum = val;
  loadOrderList();
};
//钩子函数
onMounted(() => {
  getDictByType(4).then((res) => {
    typeList.value = res.data.data;
  });
  loadProdInfoList();
  loadOrderList();
});
</script>
